//
//  ViewController.swift
//  AutoCoder
//
//  Created by lelouch on 2025/1/19.
//

import Cocoa

enum ViewType : String {
    case label          =   "Label"
    case button         =   "Button"
    case imageView      =   "ImageView"
    case tableView      =   "TableView"
    case view           =   "View"
    case field          =   "TextField"
    case name           =   ""
}

enum LayoutType : Int {
    case frame
    case constr
}

enum CodeType : Int {
    case oc
    case swift
}

class NameModel: NSObject {
    
    var name : String = ""
    
    var date : Int64 = 1
    
}

struct ViewModel {
    
    var name : String = ""
    
    var type : ViewType
    
    var codeType : CodeType
    
    var propertyDesc : String = ""
    
    var implDesc : String = ""
    
    var selectDesc : String = ""
    
    var userFrame : Bool
    
    init(type: ViewType, name : String, userFrame : Bool, codeType : CodeType) {
        self.userFrame = type == .label ? false : userFrame
        self.codeType = codeType
        self.name = name + type.rawValue
        self.type = type
        self.propertyDesc = codeType == .oc ? "\n@property (nonatomic, strong) UI\(type.rawValue) *\(self.name);\n" : ""
        if codeType == .oc {
            self.implDesc.append("\n-(UI\(type.rawValue) *)\(self.name) {\n")
            self.implDesc.append("    if (!_\(self.name)) {\n")
        } else {
            self.implDesc.append("\n    lazy var \(self.name): UI\(type.rawValue) = {\n")
        }
        var impls : [String] = []
        if codeType == .oc {
            if self.userFrame {
                if arc4random() % 2 == 0 {
                    self.implDesc.append("        _\(self.name) = [[UI\(type.rawValue) alloc] initWithFrame:CGRectMake(_, _, _, _)];\n")
                } else {
                    self.implDesc.append("        _\(self.name) = [[UI\(type.rawValue) alloc] init];\n")
                    impls.append("        _\(self.name).frame = CGRectMake(_, _, _, _);\n")
                }
            } else {
                self.implDesc.append("        _\(self.name) = [[UI\(type.rawValue) alloc] init];\n")
                impls.append("        [_\(self.name) mas_makeConstraints:^(MASConstraintMaker *make) {\n            make.left.offset(_);\n            make.top.offset(_);\n            make.width.offset(_);\n            make.height.offset(_);\n        }];\n")
            }
            self.implDesc.append("        [self.dh_contentView addSubview:_\(self.name)];\n")
        } else {
            if self.userFrame {
                switch arc4random() % 3 {
                case 0:
                    self.implDesc.append("        let _\(self.name) = UI\(type.rawValue).init(frame: CGRect(x: _, y: _, width: _, height: _))\n")
                case 1:
                    self.implDesc.append("        let _\(self.name) = UI\(type.rawValue).init()\n")
                    impls.append("        _\(self.name).frame = CGRect(x: _, y: _, width: _, height: _)\n")
                case 2:
                    self.implDesc.append("        let _\(self.name) = UI\(type.rawValue)()\n")
                    impls.append("        _\(self.name).frame = CGRect(x: _, y: _, width: _, height: _)\n")
                default:
                    break
                }
            } else {
                switch arc4random() % 2 {
                case 0:
                    self.implDesc.append("        let _\(self.name) = UI\(type.rawValue).init()\n")
                case 1:
                    self.implDesc.append("        let _\(self.name) = UI\(type.rawValue)()\n")
                default:
                    break
                }
                impls.append("        _\(self.name).snp.makeConstraints { make in\n            make.left.equalTo(_)\n            make.top.equalTo(_)\n            make.width.equalTo(_)\n            make.height.equalTo(_)\n        }\n")
            }
            self.implDesc.append("        self.view.addSubview(_\(self.name))\n")
        }
        switch type {
            case .label:
                if self.codeType == .oc {
                    impls.append("        _\(self.name).textColor = rgba(_, _, _, _);\n")
                    impls.append("        _\(self.name).font = DHFontMediumS(_);\n")
                    impls.append("        _\(self.name).textAlignment = NSTextAlignmentLeft;\n")
                    impls.append("        _\(self.name).text = _;\n")
                } else {
                    impls.append("        _\(self.name).textColor = rgba(_, _, _, _)\n")
                    impls.append("        _\(self.name).textAlignment = .left\n")
                    if arc4random() % 2 == 0 {
                        impls.append("        _\(self.name).font = UIFont.systemFont(ofSize: _, weight: .bold)\n")
                    } else {
                        impls.append("        _\(self.name).font = UIFont.systemFont(ofSize: _)\n")
                    }
                    impls.append("        _\(self.name).text = _\n")
                }
            case .button:
                if self.codeType == .oc {
                    let selectName : String = self.name.replacingOccurrences(of: "Button", with: "Func:")
                    impls.append("        [_\(self.name) setImage:[UIImage imageNamed:_] forState:UIControlStateNormal];\n")
                    impls.append("        _\(self.name).titleLabel.font = DHFontS(_);\n")
                    impls.append("        [_\(self.name) setTitleColor:rgba(_, _, _, _) forState:UIControlStateNormal];\n")
                    impls.append("        [_\(self.name) setTitle:_ forState:UIControlStateNormal];\n")
                    impls.append("        [_\(self.name) addTarget:self action:@selector(\(selectName)) forControlEvents:UIControlEventTouchUpInside];\n")
                    self.selectDesc.append("\n-(void)\(selectName)(UIButton *)sender {}\n")
                } else {
                    let selectName : String = self.name.replacingOccurrences(of: "Button", with: "Func")
                    impls.append("        _\(self.name).setImage(UIImage.init(named: ), for: .normal)\n")
                    if arc4random() % 2 == 0 {
                        impls.append("        _\(self.name).titleLabel?.font = UIFont.systemFont(ofSize: _)\n")
                    } else {
                        impls.append("        _\(self.name).titleLabel?.font = UIFont.systemFont(ofSize: _, weight: .bold)\n")
                    }
                    
                    impls.append("        _\(self.name).setTitle( , for: .normal)\n")
                    impls.append("        _\(self.name).setTitle( , for: .selected)\n")
                    impls.append("        _\(self.name).setTitleColor(rgba(_, _, _, _), for: .normal)\n")
                    impls.append("        _\(self.name).addTarget(self, action: #selector(\(selectName)), for: .touchUpInside)\n")
                    if arc4random() % 2 == 0 {
                        self.selectDesc.append("\n    @objc func \(selectName)(sender : UIButton) {}\n")
                    } else {
                        self.selectDesc.append("\n    @objc func \(selectName)() {}\n")
                    }
                }
            case .imageView:
                if self.codeType == .oc {
                    impls.append("        _\(self.name).contentMode = UIViewContentModeScaleAspectFit;\n")
                    impls.append("        _\(self.name).image = [UIImage imageNamed:_];\n")
                } else {
                    impls.append("        _\(self.name).contentMode = .scaleAspectFill\n")
                    impls.append("        _\(self.name).image = UIImage.init(named: _)\n")
                }
            case .tableView:
                if self.codeType == .oc {
                    impls.append("        _\(self.name).delegate = self;\n")
                    impls.append("        _\(self.name).dataSource = self;\n")
                    impls.append("        _\(self.name).separatorStyle = UITableViewCellSeparatorStyleNone;\n")
                    impls.append("        _\(self.name).showsVerticalScrollIndicator = NO;\n")
                    impls.append("        _\(self.name).showsHorizontalScrollIndicator = NO;\n")
                    impls.append("        if (@available(iOS 15.0, *)) {\n            _\(self.name).sectionHeaderTopPadding = 0;\n        }\n")
                    impls.append("        [_\(self.name) registerCell:@[]];\n")
                } else {
                    impls.append("        _\(self.name).delegate = self\n")
                    impls.append("        _\(self.name).dataSource = self\n")
                    impls.append("        _\(self.name).separatorStyle = .none\n")
                    impls.append("        _\(self.name).showsVerticalScrollIndicator = false\n")
                    impls.append("        _\(self.name).showsHorizontalScrollIndicator = false\n")
                    impls.append("        if #available(iOS 15.0, *) {\n            _\(self.name).sectionHeaderTopPadding = 0\n        }\n")
                }
            case .view:
//            if self.codeType == .oc {
//                impls.append("        [_\(self.name) dh_corner:_];\n")
//                impls.append("        _\(self.name).backgroundColor = rgba(_, _, _, _);\n")
//            } else {
//                impls.append("        _\(self.name).backgroundColor = rgba(0, 0, 0, 0)\n")
//                impls.append("        _\(self.name).layer.masksToBounds = true\n")
//                impls.append("        _\(self.name).layer.cornerRadius = 0\n")
//                impls.append("        _\(self.name).layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMinYCorner, .layerMaxXMaxYCorner]\n")
//            }
                break
            case .field:
                if self.codeType == .oc {
                    impls.append("        _\(self.name).textColor = rgba(_, _, _, 1);\n")
                    impls.append("        _\(self.name).placeholder = _;\n")
                    impls.append("        _\(self.name).font = DHFontS(_);\n")
                    impls.append("        _\(self.name).keyboardType = UIKeyboardTypeDefault;\n")
                } else {
                    impls.append("        _\(self.name).textColor = rgba(_, _, _, _)\n")
                    impls.append("        _\(self.name).placeholder = \n")
                    if arc4random() % 2 == 0 {
                        impls.append("        _\(self.name).font = UIFont.systemFont(ofSize: _)\n")
                    } else {
                        impls.append("        _\(self.name).font = UIFont.systemFont(ofSize: _, weight: .bold)\n")
                    }
                    impls.append("        _\(self.name).keyboardType = .default\n")
                }
        case .name:
            self.propertyDesc = self.name
            self.implDesc = ""
        }
        if self.codeType == .oc {
            impls.append("        _\(self.name).backgroundColor = rgba(_, _, _, 1);\n")
            impls.append("        [_\(self.name) dh_corner:_];\n")
        } else {
            impls.append("        _\(self.name).backgroundColor = rgba(_, _, _, _)\n")
            impls.append("        _\(self.name).layer.masksToBounds = true\n")
            impls.append("        _\(self.name).layer.cornerRadius = _\n")
            impls.append("        _\(self.name).layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMinYCorner, .layerMaxXMaxYCorner]\n")
        }
        for impl in impls.shuffled() {
            self.implDesc.append(impl)
        }
        if self.codeType == .oc {
            self.implDesc.append("    }\n")
            self.implDesc.append("    return _\(self.name);\n")
            self.implDesc.append("}\n")
        } else {
            self.implDesc.append("        return _\(self.name)\n")
            self.implDesc.append("    }()\n")
        }
        if self.type == .name {
            self.propertyDesc = self.name + "\n"
            self.implDesc = ""
        }
    }
    
}

func rgba(_ r : CGFloat, _ g : CGFloat, _ b : CGFloat, _ a : CGFloat) -> NSColor {
    return NSColor.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)
}

class ViewController: NSViewController {
    
    lazy var clear: NSButton = self.addTypeBtn("清除", #selector(clearAll))
    
    lazy var label: NSButton = self.addTypeBtn("Label", #selector(createLabel))
    
    lazy var button: NSButton = self.addTypeBtn("Button", #selector(createButton))
    
    lazy var imageView: NSButton = self.addTypeBtn("ImageView", #selector(createImageView))
    
    lazy var tableView: NSButton = self.addTypeBtn("TableView", #selector(createTableView))
    
    lazy var viewBtn: NSButton = self.addTypeBtn("View", #selector(createView))
        
    lazy var addName: NSButton = self.addTypeBtn("获取变量", #selector(randomNameFunc))
    
    lazy var newPath: String = {
        let bundlePath = Bundle.main.bundlePath.components(separatedBy: "/")
        return "/" + [bundlePath[1], bundlePath[2], "Movies"].joined(separator: "/") + "/name.txt"
    }()
    
    lazy var propertyTextView: CopyTextView = {
        let textView = CopyTextView(frame: NSRect.init(x: 130, y: 10, width: 300, height: 500))
        textView.wantsLayer = true
        textView.layer?.backgroundColor = rgba(0, 0, 0, 1).cgColor
        textView.font = NSFont.systemFont(ofSize: 13)
        self.view.addSubview(textView)
        return textView
    }()
    
    lazy var implTextView: CopyTextView = {
        let textView = CopyTextView(frame: NSRect.init(x: 450, y: 10, width: 400, height: 500))
        textView.wantsLayer = true
        textView.layer?.backgroundColor = rgba(0, 0, 0, 1).cgColor
        textView.font = NSFont.systemFont(ofSize: 13)
        self.view.addSubview(textView)
        return textView
    }()
    
    lazy var nameTextView: CopyTextView = {
        let textView = CopyTextView(frame: NSRect.init(x: 10, y: 10, width: 90, height: 30))
        textView.wantsLayer = true
        textView.layer?.backgroundColor = rgba(0, 0, 0, 1).cgColor
        textView.font = NSFont.systemFont(ofSize: 13)
        textView.layer?.masksToBounds = true
        textView.layer?.cornerRadius = 6
        self.view.addSubview(textView)
        return textView
    }()
    
    lazy var frameBtn: NSButton = {
        let btn = NSButton.init(checkboxWithTitle: "随机", target: self, action: #selector(userFrameFunc))
        btn.wantsLayer = true
        btn.font = NSFont.systemFont(ofSize: 13)
        btn.titleTextColor = rgba(0, 0, 0, 1)
        btn.layer?.masksToBounds = true
        btn.layer?.cornerRadius = 6
        btn.allowsMixedState = true
        self.view.addSubview(btn)
        return btn
    }()
    
    lazy var codeBtn: NSButton = {
        let btn = NSButton.init(checkboxWithTitle: "oc", target: self, action: #selector(codeFunc))
        btn.wantsLayer = true
        btn.font = NSFont.systemFont(ofSize: 13)
        btn.titleTextColor = rgba(0, 0, 0, 1)
        btn.layer?.masksToBounds = true
        btn.layer?.cornerRadius = 6
        btn.allowsMixedState = true
        self.view.addSubview(btn)
        return btn
    }()
        
    var items : [ViewModel] = []
        
    lazy var modelCount : Int = 0
        
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.wantsLayer = true
        self.view.layer?.backgroundColor = NSColor.white.cgColor
        
//        NameModel.mp_reset()
//        if let file = Bundle.main.path(forResource: "a", ofType: "txt"), let data = try? Data.init(contentsOf: URL.init(filePath: file)), let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String] {
//            json.forEach { m in
//                NameModel.mp_model(["name":m]).mp_add()
//            }
//        }

        self.modelCount = NameModel.mp_searchAllCount()
        
        if self.modelCount == 0 {
            if let file = Bundle.main.path(forResource: "a", ofType: "txt"), let data = try? Data.init(contentsOf: URL.init(filePath: file)), let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String] {
                json.forEach { m in
                    NameModel.mp_model(["name":m]).mp_add()
                }
            }
            self.modelCount = NameModel.mp_searchAllCount()
        }
        
        frameBtn.frame = CGRect(x: 10, y: 50, width: 90, height: 30)
        codeBtn.frame = CGRect(x: 10, y: 90, width: 90, height: 30)
        
        self.addName.frame = CGRect(x: 10, y: 130, width: 90, height: 30)
                
        clear.frame = CGRect(x: addName.frame.origin.x, y: addName.frame.size.height + addName.frame.origin.y + 10, width: addName.frame.size.width, height: addName.frame.size.height)
        
        label.frame = CGRect(x: addName.frame.origin.x, y: clear.frame.size.height + clear.frame.origin.y + 10, width: addName.frame.size.width, height: addName.frame.size.height)
        
        button.frame = CGRect(x: addName.frame.origin.x, y: label.frame.size.height + label.frame.origin.y + 10, width: addName.frame.size.width, height: addName.frame.size.height)
        
        imageView.frame = CGRect(x: addName.frame.origin.x, y: button.frame.size.height + button.frame.origin.y + 10, width: addName.frame.size.width, height: addName.frame.size.height)
        
        tableView.frame = CGRect(x: addName.frame.origin.x, y: imageView.frame.size.height + imageView.frame.origin.y + 10, width: addName.frame.size.width, height: addName.frame.size.height)
        
        viewBtn.frame = CGRect(x: addName.frame.origin.x, y: tableView.frame.size.height + tableView.frame.origin.y + 10, width: addName.frame.size.width, height: addName.frame.size.height)
                
        self.propertyTextView.string = ""
        self.implTextView.string = ""
        self.nameTextView.string = ""
        self.frameBtn.state = NSControl.StateValue(-1);
        self.codeBtn.state = NSControl.StateValue(0);
        view.setFrameSize(NSSize(width: 900, height: 600))
        if let window = self.view.window {
            // 设置窗口的新大小
            window.setContentSize(NSSize(width: 900, height: 600))
        }
    }
    
    @objc func clearAll() {
        self.items.removeAll()
        self.propertyTextView.string = ""
        self.implTextView.string = ""
        self.nameTextView.string = ""
    }

    @objc func userFrameFunc() {
        switch self.frameBtn.state.rawValue {
        case 0:
            self.frameBtn.title = "约束"
        case 1:
            self.frameBtn.title = "frame"
        default:
            self.frameBtn.title = "随机"
        }
        self.frameBtn.titleTextColor = rgba(0, 0, 0, 1)
    }
    
    @objc func codeFunc() {
        switch self.codeBtn.state.rawValue {
        case 1:
            self.codeBtn.title = "swift"
        case 0:
            self.codeBtn.title = "oc"
        default:
            self.codeBtn.title = "随机"
        }
        self.codeBtn.titleTextColor = rgba(0, 0, 0, 1)
    }
    
    func randomCode() -> CodeType {
        switch self.codeBtn.state.rawValue {
        case 1:
            return .swift
        case 0:
            return .oc
        default:
            return (arc4random() % 2) == 0 ? .oc : .swift
        }
    }
    
    @objc func randomNameFunc() {
        self.items.append(ViewModel.init(type: ViewType.name, name: randomString(), userFrame: randomUserFrame(), codeType: randomCode()))
        generateCode()
    }
    
    @objc func createLabel() {
        self.items.append(ViewModel.init(type: ViewType.label, name: self.nameTextView.string.count == 0 ? randomString() : self.nameTextView.string, userFrame: randomUserFrame(), codeType: randomCode()))
        generateCode()
    }
    
    @objc func createButton() {
        self.items.append(ViewModel.init(type: ViewType.button, name: self.nameTextView.string.count == 0 ? randomString() : self.nameTextView.string, userFrame: randomUserFrame(), codeType: randomCode()))
        generateCode()
    }
    
    @objc func createImageView() {
        self.items.append(ViewModel.init(type: ViewType.imageView, name: self.nameTextView.string.count == 0 ? randomString() : self.nameTextView.string, userFrame: randomUserFrame(), codeType: randomCode()))
        generateCode()
    }
    
    @objc func createTableView() {
        self.items.append(ViewModel.init(type: ViewType.tableView, name: self.nameTextView.string.count == 0 ? randomString() : self.nameTextView.string, userFrame: randomUserFrame(), codeType: randomCode()))
        generateCode()
    }
    
    @objc func createView() {
        self.items.append(ViewModel.init(type: ViewType.view, name: self.nameTextView.string.count == 0 ? randomString() : self.nameTextView.string, userFrame: randomUserFrame(), codeType: randomCode()))
        generateCode()
    }
    
    @objc func createField() {
        self.items.append(ViewModel.init(type: ViewType.field, name: self.nameTextView.string.count == 0 ? randomString() : self.nameTextView.string, userFrame: randomUserFrame(), codeType: randomCode()))
        generateCode()
    }
    
    func generateCode() {
        var propertyDescs : String = ""
        var implDescs : String = ""
        var selectorDescs : String = ""
        for item in items {
            propertyDescs.append(item.propertyDesc)
            implDescs.append(item.implDesc)
            if item.selectDesc.count > 1 {
                selectorDescs.append(item.selectDesc)
            }
        }
        self.propertyTextView.string = propertyDescs
        self.implTextView.string = implDescs.appending(selectorDescs)
    }
    
    func addTypeBtn(_ name : String,_ action: Selector?) -> NSButton {
        let btn = NSButton.init(title: name, target: self, action: action)
        btn.bezelStyle = .rounded
        btn.isBordered = false
        btn.wantsLayer = true
        btn.layer?.backgroundColor = rgba(0, 0, 0, 1).cgColor
        btn.font = NSFont.systemFont(ofSize: 12)
        btn.titleTextColor = rgba(255, 255, 255, 1)
        btn.layer?.masksToBounds = true
        btn.layer?.cornerRadius = 6
        self.view.addSubview(btn)
        return btn
    }
    
    func randomUserFrame() -> Bool {
        switch self.frameBtn.state.rawValue {
        case 0:
            return false
        case 1:
            return true
        default:
            return (arc4random() % 2) == 0 ? true : false
        }
    }
    
    func randomString() -> String {
        var index = Int.random(in: 0..<modelCount)
        
        let date = Int64(Date().timeIntervalSince1970)
        
        var word = NameModel.mp_searchAllData { condi in
            condi.limit = 1
            condi.params = [MPSqlSearchParam("id", "\(index + 1)")]
        }.first
        
        while let m = word, date - m.date < 2592000 {
            index = Int.random(in: 0..<modelCount)
            word = NameModel.mp_searchAllData { condi in
                condi.limit = 1
                condi.params = [MPSqlSearchParam("id", "\(index + 1)")]
            }.first
        }
        
        word?.date = date
        word?.mp_refresh()
        return word?.name ?? ""
        
//        var wordM = models[index]
//        let date = Int64(Date().timeIntervalSince1970)
//        while date - wordM.date < 2592000 {
//            index = Int.random(in: 0..<models.count)
//            wordM = models[index]
//        }
//        wordM.date = date
//        wordM.mp_refresh()
//        return wordM.name
    }

}

extension NSButton {
 
    var titleTextColor : NSColor {
        get {
            let attrTitle = self.attributedTitle
            return attrTitle.attribute(NSAttributedString.Key.foregroundColor, at: 0, effectiveRange: nil) as! NSColor
        }
        set(newColor) {
            let attrTitle = NSMutableAttributedString(attributedString: self.attributedTitle)
            let titleRange = NSMakeRange(0, self.title.count)
            attrTitle.addAttributes([NSAttributedString.Key.foregroundColor: newColor], range: titleRange)
            self.attributedTitle = attrTitle
        }
    }
    
}



